package com.share.config.zooKeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryUntilElapsed;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.zookeeper.lock.ZookeeperLockRegistry;


// 使用案例
//@Autowired
//private ZookeeperLockRegistry zookeeperLockRegistry;
//
//public void doSomething() {
//        Lock lock = zookeeperLockRegistry.obtain("my-lock");
//        if (lock.tryLock()) {
//        try {
//        // TODO: 执行业务逻辑
//        } finally {
//        lock.unlock();
//        }
//        } else {
//        // TODO: 获取锁失败的处理逻辑
//        }
//        }
@Configuration
public class ZookeeperLockConfiguration {

    @Value("${zookeeper.client}")
    private String client;

    @Bean
    public CuratorFramework curatorFramework() {
        return CuratorFrameworkFactory.newClient(client, new RetryUntilElapsed(1000, 4));
    }

    @Bean
    public ZookeeperLockRegistry zookeeperLockRegistry(CuratorFramework curatorFramework) {
        return new ZookeeperLockRegistry(curatorFramework, "/locks");
    }
}

